import csv
import argparse
import re

parser = argparse.ArgumentParser()
parser.add_argument('-t', '--targetF', required=True, help='Target file')
parser.add_argument('-s', '--srcF', required=True, help='Source file')
parser.add_argument('-k', '--k', type=float, default='1')
args = parser.parse_args()

header = []
informationList = {}

# 读取现有信息
with open(args.targetF, 'r', encoding='utf-8') as f:
    freader = csv.reader(f)
    for i, row in enumerate(freader):
        if i == 0:
            for ii, item in enumerate(row):
                if ii == 0:
                    continue
                header.append(item)
        else:
            for ii, item in enumerate(row):
                if ii == 0:
                    informationList[row[0]] = {}
                else:
                    informationList[row[0]][header[ii - 1]] = row[ii]

# 逐行读取
with open(args.srcF, 'r', encoding='utf-8') as f:
    log = f.readline()
    logHeader = log.split('\t')
    while True:
        log = f.readline()
        if log == '':
            break
        s = log.split('\t')
        idx = 0
        for i in range(len(s) - 1):
            if logHeader[i] == '序号':
                idx = s[i]
            elif re.match('题目', logHeader[i]):
                resLog = s[i]
                respt = resLog.split('=')
                respt[1] = float(respt[1]) * args.k
                oriRes = informationList[idx][respt[0].lower()]
                if respt[1] > float(oriRes):
                    informationList[idx][respt[0].lower()] = respt[1]
            # print(s[i])

# 文件的重命名
newTf = args.targetF
if len(newTf) < 7 or newTf[-6] != '_':
	if newTf[-1] == 'V':
		newTf = newTf.replace('.CSV', '_1.CSV')
	else:
		newTf = newTf.replace('.csv', '_1.csv')
else:
	newx = int(newTf.split('_')[-1].split('.')[0])
	if newTf[-1] == 'V':
		newTf = newTf.replace(newTf.split('_')[-1], str(newx + 1) + '.CSV')
	else:
		newTf = newTf.replace(newTf.split('_')[-1], str(newx + 1) + '.csv')

with open(newTf, 'w', encoding='utf-8') as f:
    f.write('序号')
    for i in header:
        f.write(',' + i)
    f.write('\n')
    for i in informationList:
        f.write(i)
        for j in informationList[i]:
            f.write(',' + str(informationList[i][j]))
        f.write('\n')
print(1)
